﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Interface;
using NetDon.OA.Interface.eLogistics;
using NetDon.OA.Portal.Components;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{
    public partial class ChooseOrderForInvoice : NavigationPageBase
    {
        public Guid Id
        {
            get { return Parameters.GetGuid("Id"); }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                CancelButton = btnCancel;
      
                //txtConfirmStatementofAccountDateStart.Text =
                //txtDueInvoiceDateStart.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
            
                //txtConfirmStatementofAccountDateEnd.Text =
                //txtDueInvoiceDateEnd.Text = DateTime.Now.ToString("yyyy-MM-dd");

                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }



                this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);

                LoadOrders();

            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
            {
                dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
            };


        }

        protected RevenueMachineAccountForInvoiceSearchCriteria GetSearchCriteria()
        {
            var criteria = new RevenueMachineAccountForInvoiceSearchCriteria
            {

            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }


            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtConfirmStatementofAccountDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtConfirmStatementofAccountDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtConfirmStatementofAccountDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtConfirmStatementofAccountDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ConfirmStatementofAccountDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            dateStart = null; dateEnd = null;
            if (!string.IsNullOrEmpty(txtDueInvoiceDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtDueInvoiceDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtDueInvoiceDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtDueInvoiceDateEnd.Text.Trim());
            }
            if ((dateStart.HasValue || dateEnd.HasValue))
            {
                criteria.DueInvoiceDate = new Range<DateTime?>(dateStart, dateEnd);
            }


            if (radioIsInvoiceNeededYes.Checked)
            {
                criteria.IsStatementofAccountCompleted = true;
            }

            criteria.IsInvoiced = false;
            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }


            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }

            return criteria;
        }
        private void LoadOrders()
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();

            this.grdInvoiceOrder.DataSource = service.GetRevenueMachineAccountForInvoices(GetSearchCriteria());
            this.grdInvoiceOrder.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadOrders();
        }

        protected void grdInvoiceOrder_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
                e.Row.Attributes["IssuingOrderId"] = Convert.ToString(DataBinder.Eval(entity, "IssuingOrderId"));
                e.Row.Attributes["StateofAccountAmount"] = Convert.ToString(DataBinder.Eval(entity, "StateofAccountAmount"));

            }
        }


        public IList<RevenueMachineAccountForInvoice> CheckItemSelection()
        {
            var selectedUsers = new List<RevenueMachineAccountForInvoice>();

            foreach (GridViewRow row in grdInvoiceOrder.Rows)
            {
                var chkSelected = (CheckBox)row.FindControl("chkSelect");
                if (chkSelected != null)
                {
                    if (chkSelected.Checked)
                    {
                        var id = row.Attributes["Id"].ToGuid();
                        var issuingOrderId = row.Attributes["IssuingOrderId"].ToGuid();
                        var stateofAccountAmount = row.Attributes["StateofAccountAmount"].ToDecimal();

                        selectedUsers.Add(new RevenueMachineAccountForInvoice()
                        {
                            RevenueMachineAccountId = id,
                            IssuingOrderId = issuingOrderId,
                            StateofAccountAmount = stateofAccountAmount
                        });
                    }
                }
            }


            return selectedUsers;
        }

        protected void btnChoose_Click(object sender, EventArgs e)
        {
            var selectedUsers = CheckItemSelection();
            if (selectedUsers.Count > 0)
            {
                var revenueMachineAccountForInvoices = new RevenueMachineAccountForInvoices()
                                                           {
                                                               IssuingOrderIds = selectedUsers.Select(o=>o.IssuingOrderId.ToString()).Aggregate((a, b) => a + "," + b),
                                                               RevenueMachineAccountIds = selectedUsers.Select(o => o.RevenueMachineAccountId.ToString()).Aggregate((a, b) => a + "," + b),
                                                               TotalStateofAccountAmount = selectedUsers.Sum(a => a.StateofAccountAmount)

                                                           };
                var serializer = new DataContractJsonSerializer(typeof(RevenueMachineAccountForInvoices));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, revenueMachineAccountForInvoices);
                stream.Position = 0;
                var sr = new StreamReader(stream);
                string resultStr = sr.ReadToEnd();
                sr.Close();
                stream.Close();
                CloseWindow(resultStr);
            }
            else
            {
                base.Alert("请选择已经对账的订单.");
                return;
            }

        }
    }


    public class RevenueMachineAccountForInvoice
    {
        public Guid RevenueMachineAccountId { get; set; }
        public Guid IssuingOrderId { get; set; }
        public decimal? StateofAccountAmount { get; set; }
    }

    [DataContract]
    public class RevenueMachineAccountForInvoices
    {
        [DataMember]
        public string RevenueMachineAccountIds { get; set; }
        [DataMember]
        public string IssuingOrderIds { get; set; }
        [DataMember]
        public decimal? TotalStateofAccountAmount { get; set; }
    }
}